﻿using B.S.BasicData.Api.Read.Application.Command.Account;
using B.S.BasicData.Domain.Entities;
using B.S.BasicData.ErrorCode;
using B.S.BasicData.Infrastructure.Interfaces;
using B.S.BasicData.Infrastructure.Utils;
using MD5Hash;
using MediatR;

namespace B.S.BasicData.Api.Read.Application.CommandHandler.Account
{

    /// <summary>
    /// 中介者登录处理类
    /// </summary>
    public class LoginAccountHandler : IRequestHandler<LoginAccountCommand, ApiResult<int>>
    {
        private readonly ILogger<LoginAccountHandler> logger;//日志
        private readonly IBaseRepository<AccountModel> accRepo;//仓储

        public LoginAccountHandler(ILogger<LoginAccountHandler> logger,IBaseRepository<AccountModel> accRepo)
        {
            this.logger = logger;
            this.accRepo = accRepo;
        }
        /// <summary>
        /// 登录的处理方法
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public Task<ApiResult<int>> Handle(LoginAccountCommand request, CancellationToken cancellationToken)
        {
            logger.LogInformation($"用户{request.AccountName}正在登录");

            ApiResult<int> result = new ApiResult<int>();//定义响应包装类 apiresult

            //根据用户名查询要登陆的用户
            var account = accRepo.Query().Result.Where(x => x.AccountName == request.AccountName).FirstOrDefault();

            if (account == null)
            {//用户不存在
                result.Code = ApiEnums.LoginUserNotExisit;
                result.Msg = ApiEnums.LoginUserNotExisit.Descrption();
                result.Data = 0;
                logger.LogInformation($"用户{request.AccountName}不存在!");
            }
            else {
                if (account.AccountPass != request.AccountPass.GetMD5())
                {
                    result.Code = ApiEnums.LoginPasswordError;
                    result.Msg = ApiEnums.LoginPasswordError.Descrption();
                    result.Data = -1;
                    logger.LogInformation($"用户{request.AccountName}密码不正确!");
                }
                else {
                    result.Code = ApiEnums.LoginOk;
                    result.Msg = ApiEnums.LoginOk.Descrption();
                    result.Data = 1;
                    logger.LogInformation($"用户{request.AccountName}登录成功!");
                }
            }
            return Task.FromResult(result);
        }
    }
}
